package io.jft.doll.ui.gameHistory

import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.g.base.api.ErrorCode
import com.g.base.extend.observeEx
import com.g.base.extend.resultNotNull
import com.g.base.room.entity.UserEntity
import com.g.base.room.repository.ListStatus
import com.g.base.room.repository.Status
import com.g.base.router.RouteExtras
import com.g.base.ui.BaseActivity
import com.g.base.ui.recyclerView.decoration.LinearItemDecoration
import com.g.base.ui.recyclerView.item.BaseItem
import com.g.base.ui.recyclerView.setupRecyclerView
import io.jft.doll.R
import io.jft.doll.databinding.ViewRecycleBinding
import io.jft.doll.model.viewModel.GameHistoryViewModel
import io.jft.doll.room.entity.remote.GameHistoryListREntity
import io.jft.doll.router.RouterPage
import io.jft.doll.ui.gameHistory.bind.GameHistoryBind
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Created by G on 2017/12/5 0005.
 */
@Route(path = RouterPage.GameHistoryActivity, extras = RouteExtras.NeedOauth)
class GameListActivity : BaseActivity<ViewRecycleBinding>() {
    override var hasToolbar: Boolean = true
    private var listStatus = ListStatus.Content
    private val gameHistoryViewModel by lazy { ViewModelProviders.of(this).get(GameHistoryViewModel::class.java) }
    private val adapter by lazy { setupRecyclerView(contentView.recyclerView) }
    private val data = arrayListOf<GameHistoryListREntity>()

    @JvmField
    @Autowired
    var roomId: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ARouter.getInstance().inject(this)

        if (roomId == null) roomId = "-1"

        setContentView(R.layout.view_recycle)
        initView()
        obsData()
        onReload()
    }

    override fun onTokenChange(data: UserEntity?) {
        if (data == null) {
            showNeedOauth()
        } else {
            onReload()
        }
    }

    override fun onReload() {
        gameHistoryViewModel.operateGameHistory(0, roomId!!)
        listStatus = ListStatus.Content
    }

    private fun initView() {
        toolbar.title = "游戏记录"
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back_toolbar_24dp)
        toolbar.setNavigationOnClickListener { finishAfterTransition() }

        adapter.setOnLoadingListener {
            if (listStatus == ListStatus.Content) {
                gameHistoryViewModel.operateGameHistory(data.size, roomId!!)
                listStatus = ListStatus.LoadMore
            } else {
                adapter.setLoadingFailed()
            }
        }
    }

    private fun obsData() {
        gameHistoryViewModel.obsGameHistoryList()
                .resultNotNull()
                .observeEx(this) {
                    when (it.status) {
                        Status.Loading -> {
                            if (listStatus == ListStatus.Content) showLoading()
                        }
                        Status.Content -> {
                            if (it.data!!.size < gameHistoryViewModel.gameHistorySize)
                                adapter.setLoadingNoMore()
                            else
                                adapter.setLoadingSucceed()

                            if (listStatus != ListStatus.LoadMore) {
                                data.clear()
                            }

                            data.addAll(it.data!!)
                            applyData()
                            showContentView()
                            listStatus = ListStatus.Content
                        }
                        Status.Error -> {
                            if (listStatus == ListStatus.LoadMore) {
                                if (it.error?.code == ErrorCode.EMPTY)
                                    adapter.setLoadingNoMore()
                                else
                                    adapter.setLoadingFailed()
                            } else {
                                if (it.error?.code == ErrorCode.EMPTY)
                                    showEmpty(it.error?.message)
                                else
                                    showError(it.error?.message)
                            }
                            listStatus = ListStatus.Content
                        }
                    }
                }
    }

    private fun applyData() {
        adapter.diffItems.addAll(data.map { mapItem ->
            GameHistoryBind(mapItem).apply {
                setOnClickListener {
                    ARouter.getInstance().build(RouterPage.GameHistoryDetailActivity).withObject("data", mapItem).navigation(this@GameListActivity)
                }
            }
        })

        (0 until contentView.recyclerView.itemDecorationCount).forEach { contentView.recyclerView.removeItemDecorationAt(it) }
        contentView.recyclerView.addItemDecoration(LinearItemDecoration(this, 0, data.size))

        adapter.calcDiffAndDispatchUpdate(
                { baseItem: BaseItem<*>, _: Int, baseItem1: BaseItem<*>, _: Int ->
                    (baseItem as GameHistoryBind).item.id == (baseItem1 as GameHistoryBind).item.id
                },
                { baseItem: BaseItem<*>, _: Int, baseItem1: BaseItem<*>, _: Int ->
                    (baseItem as GameHistoryBind).item.id == (baseItem1 as GameHistoryBind).item.id &&
                            baseItem.item.status == baseItem1.item.status
                })
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGameFeedBackStatusChangeEvent(change: GameHistoryFeedbackChangeEvent) {
        var index = 0
        for (item in data) {
            if (item.id == change.id) {
                val get = data[index]
                get.status = get.status + 2
                break
            }
            index++
        }
    }
}